#include "pub.h"
#include "cmutex.h"

CMutex::CMutex():m_mutex(NULL) {}

CMutex::~CMutex() {}

void CMutex::InitMutex() {
#ifdef WIN32
    m_mutex = CreateMutex(NULL,FALSE,NULL);
    if (m_mutex == NULL) {
        LOG(ERR,"CreateMutex error: %d\n", GetLastError());
    }
#else
    if(pthread_mutex_init(&m_thread_mutex,NULL) != 0) {
        LOG(ERR,"Init pthread mutex fail:%s.\r\n",strrerror(errno));
    }
#endif
}

void CMutex::Lock(uint32_t miliseconds) {
#ifdef WIN32
    DWORD wait_result = 0;
    if (miliseconds == 0) {
        wait_result = WaitForSingleObject(m_mutex,INFINITE);
    }
    else {
        wait_result = WaitForSingleObject(m_mutex,(DWORD)miliseconds);
    }
    switch (wait_result) {
    case WAIT_OBJECT_0: // The thread got mutex ownership.
         LOG(ERR,"Wait mutex ok.\r\n");
         break;
    case WAIT_TIMEOUT:
         LOG(ERR,"Wait mutex timeout.\r\n");
         return; 
    case WAIT_ABANDONED:
         LOG(ERR,"Wait mutex abandoned.\r\n");
         return; 
    }
#else
    if (pthread_mutex_lock(&m_mutex) != 0) {
        LOG(ERR,"Lock mutex fail.\r\n");
    }
#endif
}

void CMutex::UnLock() {
#ifdef WIN32
    if (!ReleaseMutex(m_mutex)) { 
        LOG(ERR,"Release mutex fail.\r\n");
    } 
#else
    if (pthread_mutex_unlock(&m_mutex) != 0) {
        LOG(ERR,"Lock mutex fail,err_code:%d.\r\n",ret);
        return;
    }
#endif
}